package com.aerospace.utils;

public class SortUtils {

    //冒泡排序
    public static int[] bubbleSort(int[] array){
        for(int i =0;i<array.length-1;i++){
            for (int j = 0;j<array.length-i-1;j++){
                if (array[j]>array[j+1]){
                    int temp = array[j+1];
                    array[j+1] = array[j];
                    array[j] = temp;
                }
            }
        }
        return array;
    }



    //快速排序
    public static int[] QuickSort(int[] array, int left,int right){
        if(left<right) {
            int base = division(array,left,right);
            SortUtils.QuickSort(array,left,base-1);
            SortUtils.QuickSort(array,base+1,right);
        };
        return array;
    }
    public static int division(int[] array,int left, int right){
        int base = array[left];
        while (left<right){
            while(left<right&&base<array[right]){
                right--;
            }
            array[left] = array[right];
            while(left<right&&array[left]<base){
                left++;
            }
            array[right] = array[left];
        }
        array[left] = base;
        return left;
    }



    //选择排序
    public static int[] selectionSort(int[] array){
        int min = array[0];
        int minIndex=0,temp =0;
        for (int i = 0; i< array.length-1; i++){
            for(int j =i+1; j< array.length;j++){
                if(array[j]<min){
                    minIndex = j;
                }
            }
            temp = array[i];
            array[i] = array[minIndex];
            array[minIndex] = temp;
        }
        return array;
    }



    //插入排序
    public static int[] insertSort(int[] array){
        for (int i=1;i<array.length;i++){
            if (array[i]<array[i-1]){
                int temp = array[i];
                int k = i-1;
                for (int j=k; j>=0 && temp<array[j];j--){
                    array[j+1] = array[j];
                    k--;
                }
                array[k+1] = temp;
            }
        }
        return array;
    }

    public static void main(String[] args) {
        int[] array = new int[]{2,3,4,1};
        int[] result = new int[4];
//        result = bubbleSort(array);
//        result = QuickSort(array,0,array.length-1);
//        result = selectionSort(array);
        result = insertSort(array);
        for (int i: result){
            System.out.println(i);
        }
    }
}
